<script setup lang="ts">
import type { UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui'
import { uploadLocal } from '@/utils/localOss'
import { cloneDeep } from 'lodash-es'
type PropsState = {
  directory?: string
  max?: number
}
const props = withDefaults(defineProps<PropsState>(), {
  max: 3,
})
const urls = defineModel<string[]>({
  required: false,
  default: () => {
    return []
  },
})

const fileList = ref<UploadFileInfo[]>([])

const customRequest = (options: UploadCustomRequestOptions) => {
  uploadLocal(options, props.directory)
}
const beforeUpload = async (data: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
  const maxSize = import.meta.env.VITE_UPLOAD_IMAGE_MAX_SIZE
  if (data.file.file?.size && data.file.file.size >= maxSize * 1024 * 1024) {
    msgUtil.$message.error('上传文件大小不能超过' + maxSize + 'MB，请重新上传')
    return false
  }
  return true
}
const handFinish = () => {
  nextTick(() => {
    nextTick(() => {
      console.log(cloneDeep(fileList.value))
      console.log(
        cloneDeep(fileList.value)
          .filter((el) => el.url)
          .map((el) => {
            return el.url
          }),
      )
      urls.value = cloneDeep(fileList.value)
        .filter((el) => el.url)
        .map((el) => {
          return el.url
        })
    })
  })
}
const init = () => {
  fileList.value = cloneDeep(urls.value).map((el) => {
    const arr = el.split('/')
    const fileName = arr[arr.length - 1]
    return {
      id: fileName,
      name: fileName,
      url: el,
      thumbnailUrl: el,
      status: 'finished',
    }
  })
}
const handReset = () => {
  fileList.value = []
  urls.value = []
}
const removeChange = () => {
  nextTick(() => {
    urls.value = cloneDeep(fileList.value)
      .filter((el) => el.url)
      .map((el) => el.url)
  })
}
watch(
  urls,
  (newVal) => {
    if (newVal && newVal.length > 0) {
      if (fileList.value.length === 0) {
        init()
      }
    } else {
      if (fileList.value.length > 0) {
        handReset()
      }
    }
  },
  {
    immediate: true,
  },
)
</script>

<template>
  <n-upload
    action=""
    v-model:file-list="fileList"
    accept="image/*"
    list-type="image-card"
    :max="max"
    showPreviewButton
    :custom-request="customRequest"
    @before-upload="beforeUpload"
    @remove="removeChange"
    @finish="handFinish"
  />
</template>

<style scoped lang="scss"></style>
